import { useState, useMemo, useEffect } from "react"
import { queryModelHistorys } from "../apis/model"

/**
 * 模型版本钩子
 */
const useModelVersion = ({
  modelId,
  changeVersionAction
}) => {
  // 所有的版本
  const [versions, setVersions] = useState([])
  // 当前使用的最新版本号
  const [releaseVersion, setReleaseVersion] = useState(null)
  // 当前选中的版本号
  const [curVersion, setCurVersion] = useState(null)
  // 判断当前选中的版本是否
  const isReleaseVersion = useMemo(() => {
    return !!curVersion && curVersion === releaseVersion
  }, [curVersion, releaseVersion])

  useEffect(() => {
    doQueryVersions()
  }, [modelId])

  useEffect(() => {
    setCurVersion(releaseVersion)
  }, [versions, releaseVersion])

  // 切换版本
  const handleChangeVersion = (versionNo) => {
    setCurVersion(versionNo)
    const versionItem = versions.find(el => el.version === versionNo)
    changeVersionAction && changeVersionAction(versionItem, releaseVersion)
  }

  const curVerionId = useMemo(() => {
    const versionItem = versions.find(el => el.version === curVersion)
    return versionItem ? versionItem.id : null
  }, [curVersion])

  // 查询版本
  const doQueryVersions = async () => {
    try {
      const { data } = await queryModelHistorys(modelId)
      data.sort((a, b) => b.version - a.version)
      setVersions(data)
    } catch (error) {
      // 只有一个版本的时候后端不返回数据情况的处理
      setVersions([{
        id: 1,
        version: 1
      }])
      // message.error('版本查询失败')
    }
  }

  return {
    versions,
    doQueryVersions,
    releaseVersion,
    setReleaseVersion,
    curVersion,
    curVerionId,
    setCurVersion,
    isReleaseVersion,
    handleChangeVersion
  }
}

export default useModelVersion